import json
import re

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User, Address
from apps.users.utils import generate_verify_token, check_verify_token
from celery_tasks.email.tasks import send_verify_mail
from utils.viewmixin import LoginMixin


class UsernameCountView(View):
    def get(self, request, username):
        print(username)

        count = User.objects.filter(username=username).count()

        return JsonResponse({"count": count, "code": "0", "errmsg": "ok"})


class RegisterView(View):
    def post(self, request):
        # 接受请求
        body_byte = request.body
        body_dict = json.loads(body_byte)
        # 获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")
        # 验证数据
        # 验证是否为空 有没有传
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": "400", "errmsg": "register fail"})

        # 正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "register fail"})

        # 短信验证码验证
        redis_cli = get_redis_connection("code")
        redis_sms_code = redis_cli.get("sms_%s" % mobile)
        # 判断是否过期
        if redis_sms_code is None:
            return JsonResponse({"code": 400, "errmsg": "短信验证码过期"})

        if redis_sms_code.decode().lower() != sms_code.lower():
            return JsonResponse({'code': 400, "errmsg": "短信验证码输入错误"})
        # 生成用户保存到数据库
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, "errmsg": "注册失败，请检查用户信息"})
        # 返回响应（json数据）
        login(request, user)
        return JsonResponse({"code": "0", "errmsg": "ok"})


class LoginView(View):
    def post(self, request):
        # 1 接受数据 json
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get("username")
        password = data_dict.get("password")
        remembered = data_dict.get("remembered")

        # 2 验证数据 是否为空
        if not all([username, password]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})

        # 根据用户传入的username的值 判断是手机号还是用户名
        # 然后设置用户验证是使用手机号还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 3 验证用户名和密码是否正确
        # 如果用户名密码正确 返回User对象 否则返回None
        user = authenticate(username=username, password=password)

        if user is None:
            return JsonResponse({"code": "400", "errmsg": "用户名或者密码错误"})

        # 4 状态保持  session
        login(request, user)

        # 5 判断是否记住登录 设置session的有效期
        if remembered:
            # 记住登录 默认2周
            request.session.set_expiry(None)

        else:
            # 不记住登录  浏览器关闭 session过期
            request.session.set_expiry(0)

        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 6 返回响应
        return response


class LogoutView(View):
    def delete(self, request):
        logout(request)
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        response.delete_cookie('username')

        return response


class UserInfoView(LoginMixin, View):
    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active,
        }

        return JsonResponse({
            "code": 0,
            "errmsg": "个人中心",
            "info_data": info_data,
        })


class SaveEmailView(View):
    def put(self, request):
        # 获取数据 邮箱地址
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get("email")

        # 校验数据
        if not email:
            return JsonResponse({"code": "400", "errmsg": "邮箱地址不能为空"})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({"code": "400", "errmsg": "邮箱地址格式有误"})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "邮箱保存失败"})

        # 发送邮件
        subject = "美多商城验证邮箱"
        recipient_list = [email]

        token = generate_verify_token(request.user.id)
        verify_url = "http://192.168.191.152:8080/success_verify_email.html?token=%s" % token

        html_message = '<p>尊敬的用户你好！</p>' \
                       '<p>感谢你使用美多商城</p>' \
                       '<p>你的邮箱为 %s ,请点击此链接激活你的邮箱</p>' \
                       '<p><a href="%s">%s</a></p>' % (email, verify_url, verify_url)
        send_verify_mail.delay(subject=subject, html_message=html_message, recipient_list=recipient_list)

        return JsonResponse({"code": "0", "errmsg": "ok"})


class EmailVerifyView(View):
    def put(self, request):

        token = request.GET.get("token")

        if token is None:
            return JsonResponse({"code": "400", "errmsg": "token为空"})
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({"code": "400", "errmsg": "token错误"})
        try:
            user = User.objects.get(id=user_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "查询不到用户"})

        user.email_active = True
        user.save()

        return JsonResponse({"code": "0", "errmsg": "ok"})


class AddreassCreateView(LoginMixin, View):

    def post(self, request):
        # - 1接收请求
        body = request.body
        data_dict = json.loads(body)
        # - 2获取参数
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        # - 3验证参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({"code": "400", "errmsg": "请输入正确的手机号码"})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({"code": "400", "errmsg": "请输入正确的邮件地址"})

        user = request.user
        # - 4保存数据到数据库
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
        except Exception as e:
            print(e)
            return JsonResponse({"code": "400", "errmsg": "保存数据失败"})

        # - 5返回响应
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({"code": "0", "errmsg": "ok", "address": address_dict})


class AddressView(LoginMixin, View):

    def get(self, request):
        # 获取用户对象
        user = request.user
        # 查询当前用户的所有地址信息
        try:
            address_obj = Address.objects.filter(user=user, is_deleted=False)
        except Exception:
            return JsonResponse({"code": "400", "errmsg": "查询失败"})
        # 转为字典数据
        address_list = []
        for address in address_obj:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email,
            })
        # 返回
        return JsonResponse({"code": "0", "errmsg": "ok", "addresses": address_list})


class AlteraddressView(LoginMixin, View):

    def delete(self, request, id):
        try:
            address = Address.objects.get(id=id)
            address.is_deleted = True
            address.save()
        except Exception:
            return JsonResponse({"code": "400", "errmsg": "删除失败"})

        return JsonResponse({"code": "0", "errmsg": "ok"})

    def put(self, request, id):
        try:
            address = Address.objects.get(id=id)
            body = request.body
            address_dict = json.loads(body)
            address.receiver = address_dict.get("receiver")
            address.province_id = address_dict.get("province_id")
            address.city_id = address_dict.get("city_id")
            address.district_id = address_dict.get("district_id")
            address.place = address_dict.get("place")
            mobile = address_dict.get("mobile")
            tel = address_dict.get("tel")
            email = address_dict.get("email")

            if not re.match(r'^1[3-9]\d{9}$', mobile):
                return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

            if tel:
                if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                    return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
            if email:
                if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                    return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

            address.mobile = mobile
            address.tel = tel
            address.email = email
            address.save()
        except Exception as e:
            print('-------------------------------------------', e)
            return JsonResponse({"code": "400", "errmsg": "修改失败"})

        return JsonResponse({"code": "0", "errmsg": "ok"})


class AlterpasswordView(View):
    def put(self, request):
        user = request.user
        body = request.body
        user_dict = json.loads(body)
        old_password = user_dict.get("old_password")
        new_password = user_dict.get("new_password")
        if not user.check_password(old_password):
            return JsonResponse({"code": "400", "errmsg": "原密码错误"})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})

            # 清理状态保持信息
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response
